package com.ztk.threadbasic.excel.handler;

import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.AbstractCellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

public class PercentageCellWriteHandler extends AbstractCellWriteHandler {

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) {
            // 处理表头，如果需要的话
            return;
        }

        if (CollectionUtils.isEmpty(cellDataList)) {
            return;
        }

        if (cell.getCellType() != CellType.NUMERIC) {
            return;
        }

        int columnIndex = cell.getColumnIndex();
        if (columnIndex < 2) {
            return;
        }

        int rowIndex = cell.getRowIndex();
        if (rowIndex < 22) {
            return;
        }

        double numericCellValue = cell.getNumericCellValue();
        if ("0.0".equals(String.valueOf(numericCellValue))) {
            return;
        }

//        cell.setCellValue(numericCellValue * 100);
        CellStyle cellStyle = writeSheetHolder.getSheet().getWorkbook().createCellStyle();
        cellStyle.setDataFormat(writeSheetHolder.getSheet().getWorkbook().createDataFormat().getFormat("#,##0.00%"));
        cell.setCellStyle(cellStyle);

//
//
//        WriteCellData<?> writeCellData = cellDataList.get(0);
//        BigDecimal numberValue = writeCellData.getNumberValue();
//        String percentageString  = String.format("%.2f%%", numberValue.doubleValue() * 100);
//
//        cellStyle = writeSheetHolder.getSheet().getWorkbook().createCellStyle();
//        cellStyle.setDataFormat(writeSheetHolder.getSheet().getWorkbook().createDataFormat().getFormat("0.00%"));
//
//        // 应用样式到单元格
//        cell.setCellStyle(cellStyle);
//
//        // 设置单元格值为百分比字符串
//        cell.setCellValue(percentageString);

        // 设置单元格的数据类型为百分比
//        Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
//        CellStyle cellStyle = workbook.createCellStyle();
//        cellStyle.setDataFormat(workbook.createDataFormat().getFormat("0.00%"));
//        cell.setCellStyle(cellStyle);
    }
}
